package org.marketing.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @describe 读取FTP上的文件
 * @auto li.wang
 * @date 2013-11-18 下午4:07:34
 */
public class FtpUtils {

	private static Logger logger = LoggerFactory.getLogger(FtpUtils.class);

	private FTPClient ftpClient;
	private String fileName;
	private String strencoding;
	private String ip = "";// "113.108.96.3"; // 服务器IP地址
	private String userName = "test"; // 用户名
	private String userPd = "test"; // 密码
	private int port = 21; // 端口号
	private String path = "/SZX348/OPFQ/"; // 读取文件的存放目录

	/**
	 * init ftp servere
	 */
	public FtpUtils(String ip, String userName, String userPwd, int port, String path, String fileName) {
		this.ip = ip;
		this.userName = userName;
		this.userPd = userPwd;
		this.port = port;
		this.path = path;
		this.fileName = fileName;
		this.reSet();
	}

	public void reSet() {
		strencoding = "UTF-8";
		this.connectServer(ip, port, userName, userPd, path);
	}

	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * @throws SocketException
	 * @throws IOException
	 *             function:连接到服务器
	 */
	public void connectServer(String ip, int port, String userName, String userPwd, String path) {
		ftpClient = new FTPClient();
		try {
			// 连接
			ftpClient.connect(ip, port);
			// 登录
			ftpClient.login(userName, userPwd);
			if (path != null && path.length() > 0) {
				// 跳转到指定目录
				ftpClient.changeWorkingDirectory(path);
			}
		} catch (Exception e) {
			logger.error("连接异常" + e.getMessage());
		}
	}

	/**
	 * @throws IOException
	 *             function:关闭连接
	 */
	public void closeServer() {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (Exception e) {
				logger.error("关闭连接异常" + e.getMessage());
			}
		}
	}

	/**
	 * @param path
	 * @return function:读取指定目录下的文件名
	 * @throws IOException
	 */
	public List<String> getFileList(String path) {
		List<String> fileLists = new ArrayList<>();
		// 获得指定目录下所有文件名
		FTPFile[] ftpFiles = null;
		try {
			ftpFiles = ftpClient.listFiles(path);
		} catch (Exception e) {
			logger.error("读取异常" + e.getMessage());
		}
		for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
			FTPFile file = ftpFiles[i];
			if (file.isFile()) {
				fileLists.add(file.getName());
			}
		}
		return fileLists;
	}

	/**
	 * @param fileName
	 * @return function:从服务器上读取指定的文件
	 * @throws ParseException
	 * @throws IOException
	 */
	public String readFile() throws ParseException {
		InputStream ins = null;
		StringBuilder builder = new StringBuilder(150);
		try {
			// 从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName);
			BufferedReader reader = new BufferedReader(new InputStreamReader(ins, strencoding));
			String line;

			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			reader.close();
			if (ins != null) {
				ins.close();
			}
			// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
			ftpClient.getReply();
		} catch (Exception e) {
			logger.error("读取异常" + e.getMessage());
		}
		return builder.toString();
	}

	/**
	 * @param fileName
	 *            function:删除文件
	 */
	public void deleteFile(String fileName) {
		try {
			ftpClient.deleteFile(fileName);
		} catch (Exception e) {
			logger.error("删除异常" + e.getMessage());
		}
	}

	/**
     * 获取主机名称
     * @return  string
     */
    public static String getHostName(){
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "";
        }
    }

    /**
     * 获取UUID
     * @return  String
     *
     */
    public static String getUUID(){
        return UUID.randomUUID().toString();
    }
}